import axios from "axios"
import { Message } from 'element-ui'

let baseUrls = {
  "http://172.20.48.90:8000":"http://172.20.48.90:8090/workcount",
  "http://localhost:8080":"http://localhost:8090/workcount",
  "http://www.sunvanai.com":"http://www.sunvanai.com:9091/sangwan",
  "http://123.57.36.253:8080":"http://123.57.36.253:8090/workcount"
}
let localUrl = window.location.origin
 let baseURL = baseUrls[localUrl]

const service = axios.create({
    baseURL:  baseURL,
    timeout: 500000
})

/**
 * 请求拦截器
 */
service.interceptors.request.use(
    config => {
        return config
    },
    err => {
        console.log(err)
        Promise.reject(err)
    }
)
/**
 * 响应拦截器
 */
service.interceptors.response.use(
    response => {
        const res = response.data
        const code = [500, 404, 403, 401]
        if (!code.includes(res.code)) return response
        Message({
            showClose: true,
            message: res.code,
            type: 'error'
        })
        return response
    },
    error => {
        Message({
            showClose: true,
            message: '网络错误,请稍后重试',
            type: 'error'
        })
        return Promise.reject(error)
    }
)

export default service

export const get = (url, params) =>
    new Promise((resolve, reject) => {
        service({
            url: url,
            method: 'get',
            params
        })
            .then(res => {
                Message({
                    showClose: true,
                    message: res.data.msg
                })
                resolve(res.data)
            })
            .catch(err => { reject(err.data) })
    })

export const post = (url, params) =>
    new Promise((resolve, reject) => {
        service({
            url: url,
            method: 'post',
            data:params
        })
            .then(res => {
                if (res.data.msg) {
                    Message({
                        showClose: true,
                        message: res.data.msg
                    })
                }

                resolve(res.data)
            })
            .catch(err => {
                reject(err.data)
            })
    })


export const fileUpload = (url, params) =>
  new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'post',
      data:params,
      headers:{
        'Content-Type':'multipart/form-data'
      }
    })
      .then(res => {
        if (res.data.msg) {
          Message({
            showClose: true,
            message: res.data.msg
          })
        }

        resolve(res.data)
      })
      .catch(err => {
        reject(err.data)
      })
  })